//
//  NSString+FontSize.m
//  CheFu365
//
//  Created by safiri on 2017/11/1.
//  Copyright © 2017年 safiri. All rights reserved.
//

#import "NSString+FontSize.h"

@implementation NSString (FontSize)

//单行的
- (CGSize)textSizeWithFont:(UIFont*)font {
    
    CGSize textSize = [self sizeWithAttributes:@{NSFontAttributeName:font}];
    textSize = CGSizeMake((int)ceil(textSize.width), (int)ceil(textSize.height));
    return textSize;
}

/**
 根据字体、行数、行间距和constrainedWidth计算多行文本占据的size
 **/
- (CGSize)textSizeWithFont:(UIFont*)font
             numberOfLines:(NSInteger)numberOfLines
               lineSpacing:(CGFloat)lineSpacing
          constrainedWidth:(CGFloat)constrainedWidth
          isLimitedToLines:(BOOL *)isLimitedToLines {
    
    if (self.length == 0) {
        return CGSizeZero;
    }
    CGFloat oneLineHeight = font.lineHeight;
    CGSize textSize = [self boundingRectWithSize:CGSizeMake(constrainedWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
    
    CGFloat rows = textSize.height / oneLineHeight;
    CGFloat realHeight = oneLineHeight;
    // 0 不限制行数
    if (numberOfLines == 0) {
        if (rows >= 1) {
            realHeight = (rows * oneLineHeight) + (rows - 1) * lineSpacing;
        }
    }else{
        if (rows > numberOfLines) {
            rows = numberOfLines;
            if (isLimitedToLines) {
                *isLimitedToLines = YES;  //被限制
            }
        }
        realHeight = (rows * oneLineHeight) + (rows - 1) * lineSpacing;
    }
    
    return CGSizeMake(ceil(constrainedWidth),ceil(realHeight));
}

- (CGFloat)calculateShowHeightWithFont:(UIFont *)font fontColor:(UIColor *)fontColor showWidth:(CGFloat)width
{
    if (self == nil) {
        return 0;
    }
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    NSDictionary *dic = @{NSFontAttributeName:font,NSForegroundColorAttributeName:fontColor};
    
    CGFloat textHeight;
    CGRect rect = [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:options attributes:dic context:nil];
    
    textHeight = ceilf(rect.size.height);
    
    //return textHeight + 2; //加两个像素,防止emoji被切掉.
    return textHeight;
}
@end
